package com.eogo.item.service.impl;

import com.eogo.egexception.EgException;
import com.eogo.egexception.status.EgExceptionStatus;
import com.eogo.item.mapper.BrandMapper;
import com.eogo.item.pojo.Brand;
import com.eogo.item.service.BrandService;
import com.eogo.vo.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;
import java.util.List;

@Service
public class BrandServiceImpl  implements BrandService {

    @Autowired
    BrandMapper brandMapper;

    @Override
    public PageResult<Brand> queryBrandByPage(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        PageHelper.startPage(page,rows);
        Example example = new Example(Brand.class);
        if(StringUtils.isNotBlank(key)){
            //过滤条件
            example.createCriteria().orLike("name" , "%"+key + "%" )
                    .orEqualTo("letter" , key.toLowerCase());
        }
        //排序
        if (StringUtils.isNotBlank(sortBy)){
            String orderByClause = sortBy + (desc ? " DESC" : " ASC");
            example.setOrderByClause(orderByClause);
        }
        List<Brand> list = brandMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            throw new EgException(EgExceptionStatus.BRAND_NOT_FOUND);
        }
        //解析分页结果
        PageInfo<Brand> info = new PageInfo<Brand>(list);

        return new PageResult<Brand>(info.getTotal(),list);
    }

    @Transactional
    @Override
    public void saveBrand(Brand brand, List<Long> cids) {
       //新增品牌
        int count = brandMapper.insert(brand);
       if(count != 1){
           throw new EgException(EgExceptionStatus.BRAND_SAVE_ERROR);
       }
       //新增中间表
        for(Long cid : cids){
             count =  brandMapper.insertCategoryBrand(cid,brand.getId());
            if(count != 1){
                throw new EgException(EgExceptionStatus.BRAND_SAVE_ERROR);
            }
        }

    }
}
